package com.kuang.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test09 {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        // 获得class对象
        Class<?> c1 = Class.forName("com.kuang.reflection.User");

        // construct one object
        // User user = (User)c1.newInstance();  // 调用了类的无参构造器
        // System.out.println(user);

        // 通过构造器获得对象
        // Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
        // User user2 = (User)declaredConstructor.newInstance("qinjiang", 001, 18);
        // System.out.println(user2);

        // 通过反射调用普通方法
        // User user3 = (User) c1.newInstance();
        // Method setName = c1.getMethod("setName", String.class);  // 获取一个方法
        // setName.invoke(user3, "kuangshen"); // invoek one method invoke(object, param)
        // System.out.println(user3.getName());

        // 通过反射操作属性
        User user4 = (User) c1.newInstance();
        Field name = c1.getDeclaredField("name");
        // 不能直接操作private属性，必须先设置参数可见性
        name.setAccessible(true);
        name.set(user4, "狂神2");
        System.out.println(user4.getName());
    }
}
